package com.codeavatar.hardwaretester.activity.hardware.bluetooth;

import android.Manifest;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.codeavatar.catools.base.CaBaseActivity;
import com.codeavatar.catools.helper.CaActionBarHelper;
import com.codeavatar.catools.helper.CaLogHelper;
import com.codeavatar.catools.helper.CaPermissionHelper;
import com.codeavatar.catools.helper.CaReceiverHelper;
import com.codeavatar.catools.helper.CaToastHelper;
import com.codeavatar.hardwaretester.R;
import com.codeavatar.hardwaretester.adapter.BluetoothCharacteristicsListAdapter;
import com.codeavatar.hardwaretester.adapter.BluetoothDevicesListAdapter;
import com.codeavatar.hardwaretester.adapter.BluetoothServicesListAdapter;
import com.codeavatar.hardwaretester.databinding.ActivityBluetoothServerBinding;
import com.codeavatar.hardwaretester.model.BluetoothConnectModel;
import com.codeavatar.hardwaretester.model.BluetoothDeviceModel;
import com.codeavatar.hardwaretester.model.BluetoothServiceModel;
import com.codeavatar.hardwaretester.service.BluetoothBleService;

import java.util.List;

/**
 * +----------------------------------------------------------------------
 * | @Author: codeavatar   @Year：2022
 * +----------------------------------------------------------------------
 * | @Email: codeavatar@aliyun.com
 * +----------------------------------------------------------------------
 **/
public class ServerActivity extends CaBaseActivity {

    private final String TAG = this.getClass().getSimpleName();

    private ActivityBluetoothServerBinding mainBinding;
    private BluetoothAdapter bluetoothAdapter;
    private BluetoothDevicesListAdapter devicesListAdapter;
    private BluetoothServicesListAdapter servicesListAdapter;
    private BluetoothCharacteristicsListAdapter characteristicsListAdapter;
    private CaReceiverHelper caReceiverHelper;

    //++++++++++++++++++++++++++++++++++++++
    //++ 外部方法
    //++++++++++++++++++++++++++++++++++++++

    public void sendBleMsg(Bundle extras){
        caReceiverHelper.sendBroadcast(BluetoothBleService.ACTION_APP_BLE, BluetoothBleService.PERMISSION_APP_BLUETOOTH,extras);
    }

    //++++++++++++++++++++++++++++++++++++++
    //++ 内部方法
    //++++++++++++++++++++++++++++++++++++++

    private void doRefreshList(ERefreshType type){
        if(null != BluetoothBleService.init()){
            List<BluetoothDeviceModel> list = BluetoothBleService.init().getDeviceList();
            switch (type){
                case DeviceList:
                    this.devicesListAdapter.setDataList(list);
                    this.devicesListAdapter.notifyDataSetChanged();
                    break;
                case ServiceList:
                    for (BluetoothDeviceModel item:list){
                        if(item.getCheckedIndex()!=-1){
                            this.servicesListAdapter.setDataList(item.getServiceModelList());
                            this.servicesListAdapter.notifyDataSetChanged();
                            break;
                        }
                    }
                    break;
                case CharacteristicList:
                    for (BluetoothDeviceModel item:list){
                        if(item.getCheckedIndex()!=-1){
                            for (BluetoothServiceModel item2:item.getServiceModelList()){
                                if(item2.getCheckedIndex()!=-1){
                                    this.characteristicsListAdapter.setDataList(item2.getCharacteristicModelList());
                                    this.characteristicsListAdapter.notifyDataSetChanged();
                                    break;
                                }
                            }
                            break;
                        }
                    }
                    break;
            }
        }
    }

    private void doLoadData(){
        //数据适配器
        devicesListAdapter = new BluetoothDevicesListAdapter(this,mainBinding.rvwDevices);
        servicesListAdapter = new BluetoothServicesListAdapter(this,mainBinding.rvwServices);
        characteristicsListAdapter = new BluetoothCharacteristicsListAdapter(this,mainBinding.rvwCharacterstics);
        //设备
        mainBinding.rvwDevices.setLayoutManager(new LinearLayoutManager(this));
        mainBinding.rvwDevices.setAdapter(this.devicesListAdapter);
        //服务
        mainBinding.rvwServices.setLayoutManager(new LinearLayoutManager(this));
        mainBinding.rvwServices.setAdapter(this.servicesListAdapter);
        //特征
        mainBinding.rvwCharacterstics.setLayoutManager(new LinearLayoutManager(this));
        mainBinding.rvwCharacterstics.setAdapter(this.characteristicsListAdapter);
    }

    private void doButtonsEnabled(){
        mainBinding.btnOpen.setEnabled(!bluetoothAdapter.isEnabled());
        mainBinding.btnClose.setEnabled(bluetoothAdapter.isEnabled());
        if(null != BluetoothBleService.init()){
            mainBinding.btnStart.setEnabled(!BluetoothBleService.init().isEnabled());
            mainBinding.btnStop.setEnabled(BluetoothBleService.init().isEnabled());
            if(BluetoothBleService.init().isDiscovering()){
                mainBinding.btnDiscovery.setEnabled(false);
                mainBinding.btnUndiscovery.setEnabled(true);
            }else{
                mainBinding.btnDiscovery.setEnabled(true);
                mainBinding.btnUndiscovery.setEnabled(false);
            }
            mainBinding.btnConnectTester.setEnabled(BluetoothBleService.init().isEnabled());
            mainBinding.btnPingpongTester.setEnabled(BluetoothBleService.init().isEnabled());
        }else{
            mainBinding.btnStart.setEnabled(true);
            mainBinding.btnStop.setEnabled(false);
            mainBinding.btnDiscovery.setEnabled(false);
            mainBinding.btnUndiscovery.setEnabled(false);
            mainBinding.btnConnectTester.setEnabled(false);
            mainBinding.btnPingpongTester.setEnabled(false);
        }
    }

    private void doInit(){
        this.doButtonsEnabled();
        //注册接受者
        caReceiverHelper = new CaReceiverHelper(gActivity,bleChangeBroadcastReceiver);
        caReceiverHelper.registerReceiver(BluetoothBleService.ACTION_APP_BLE_CHANGE, BluetoothBleService.PERMISSION_APP_BLUETOOTH);
        //蓝牙
        //注册发现设备接受者
        IntentFilter foundFilter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
        registerReceiver(bluetoothDeviceReceiver,foundFilter);
    }

    private BroadcastReceiver bluetoothDeviceReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
           String action =  intent.getAction();
           if(BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)){
               doButtonsEnabled();
           }
        }
    };

    //蓝牙信息通道
    private BroadcastReceiver bleChangeBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            CaLogHelper.info(TAG,"[bleChangeBroadcastReceiver]接收到来自蓝牙服务的消息...");
            Bundle extras = intent.getExtras();
            if(null != extras){
                CaLogHelper.info(extras,"【"+TAG+"】[bleChangeBroadcastReceiver]蓝牙信息通道...");
                String action = extras.getString("action");
                if("ble_state_change".equals(action)){
                    doButtonsEnabled();
                }else if("ble_service_state".equals(action)){
                    doButtonsEnabled();
                }else if("ble_found_device".equals(action)){
                    doRefreshList(ERefreshType.DeviceList);
                }else if("ble_found_service".equals(action)){
                    doRefreshList(ERefreshType.ServiceList);
                }else if("ble_found_characteristic".equals(action)){
                    doRefreshList(ERefreshType.CharacteristicList);
                }else if("ble_found_finish".equals(action)){
                    //缓存要连接的UUID
                    BluetoothConnectModel bluetoothConnectModel = BluetoothBleService.init().getBluetoothConnectModel();
                    if(null != bluetoothConnectModel){
                        String vals = String.format("%s\n%s\n%s",
                                bluetoothConnectModel.getBluetoothDevice().getAddress(),
                                bluetoothConnectModel.getBluetoothGattService().getUuid().toString(),
                                bluetoothConnectModel.getBluetoothGattCharacteristic().getUuid().toString());
                        CaToastHelper.toast(gActivity, vals);
                    }
                }
            }
        }
    };

    @SuppressLint("MissingPermission")
    private void doAction(int resId) {
        Intent intent = new Intent();
        Bundle extras = new Bundle();

        switch (resId) {
            case R.id.btn_open:
                if (!bluetoothAdapter.isEnabled()) {
                    bluetoothAdapter.enable();
                }
                break;
            case R.id.btn_close:
                if (bluetoothAdapter.isEnabled()) {
                    bluetoothAdapter.disable();
                }
                break;
            case R.id.btn_start:
                intent.setClass(gActivity, BluetoothBleService.class);
                startService(intent);
//                bindService(intent, new ServiceConnection() {
//                    @Override
//                    public void onServiceConnected(ComponentName name, IBinder service) {
//
//                    }
//
//                    @Override
//                    public void onServiceDisconnected(ComponentName name) {
//
//                    }
//                },0);
                break;
            case R.id.btn_stop:
                intent.setClass(gActivity, BluetoothBleService.class);
                stopService(intent);
//                unbindService(new ServiceConnection() {
//                    @Override
//                    public void onServiceConnected(ComponentName name, IBinder service) {
//
//                    }
//
//                    @Override
//                    public void onServiceDisconnected(ComponentName name) {
//
//                    }
//                });
                break;
            case R.id.btn_discovery:
                extras.putString("action","ble_discovery");
                //向蓝牙服务广播消息
                sendBleMsg(extras);
                break;
            case R.id.btn_undiscovery:
                extras.putString("action","ble_undiscovery");
                //向蓝牙服务广播消息
                sendBleMsg(extras);
                break;
            case R.id.btn_connect_tester:
                if(null != BluetoothBleService.init()){
                    BluetoothConnectModel model = BluetoothBleService.init().getBluetoothConnectModel();
                    if(null != model){
                       if(null != model.getBluetoothDevice() && null != model.getBluetoothGattService() && null != model.getBluetoothGattCharacteristic()){
                           extras.putString("device_id",model.getBluetoothDevice().getAddress());
                           extras.putString("service_uuid",model.getBluetoothGattService().getUuid().toString());
                           extras.putString("characteristic_uuid",model.getBluetoothGattCharacteristic().getUuid().toString());
                           toStart(ConnectTesterActivity.class,extras);
                       }
                    }
                }
                break;
            case R.id.btn_pingpong_tester:
                if(null != BluetoothBleService.init()){
                    BluetoothConnectModel model = BluetoothBleService.init().getBluetoothConnectModel();
                    if(null != model){
                        if(null != model.getBluetoothDevice() && null != model.getBluetoothGattService() && null != model.getBluetoothGattCharacteristic()){
                            extras.putString("device_id",model.getBluetoothDevice().getAddress());
                            extras.putString("service_uuid",model.getBluetoothGattService().getUuid().toString());
                            extras.putString("characteristic_uuid",model.getBluetoothGattCharacteristic().getUuid().toString());
                            toStart(PingPongTesterActivity.class,extras);
                        }
                    }
                }
                break;
            default:
                CaLogHelper.warn(TAG, getResources().getString(R.string.ca_txt_no_resid));
                break;
        }
    }

    //刷新类型
    private enum ERefreshType{
        DeviceList,ServiceList,CharacteristicList
    }

    //++++++++++++++++++++++++++++++++++++++
    //++ 重写方法
    //++++++++++++++++++++++++++++++++++++++

    @Override

    protected void initBinding() {
        mainBinding = ActivityBluetoothServerBinding.inflate(getLayoutInflater());
    }

    @Override
    protected View getLayoutView() {
        return mainBinding.getRoot();
    }

    @Override
    protected void initNavigation() {
        CaActionBarHelper.init().toolbar(getSupportActionBar(), "蓝牙服务");
    }

    @Override
    protected void initView() {
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    }

    @Override
    protected void initEvent() {
        for (int i = 0; i < mainBinding.lltButtons.getChildCount(); i++) {
            mainBinding.lltButtons.getChildAt(i).setOnClickListener(this);
        }
        for (int i = 0; i < mainBinding.lltButtons2.getChildCount(); i++) {
            mainBinding.lltButtons2.getChildAt(i).setOnClickListener(this);
        }
    }

    @Override
    protected void initData() {
        this.doInit();
        this.doLoadData();
    }

    @Override
    public void onClick(View v) {
        gPermissionHelper.requestPermission(this, new String[]{
                Manifest.permission.BLUETOOTH, Manifest.permission.BLUETOOTH_ADMIN},
                new CaPermissionHelper.IActionCallback() {
            @Override
            public void onGranted() {
                doAction(v.getId());
            }

            @Override
            public void onDenied(List<String> deniedList, List<String> grantedList) {
                CaToastHelper.toast(gActivity,"请开启蓝牙相关权限！");

                CaLogHelper.info(deniedList,"拒绝权限");
                CaLogHelper.info(grantedList,"已授权限");
            }
        });
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        int itemId = item.getItemId();
        if (android.R.id.home == itemId) {
            this.finish();
        } else {
            return super.onOptionsItemSelected(item);
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        gPermissionHelper.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        caReceiverHelper.unregisterReceiver();
        unregisterReceiver(this.bluetoothDeviceReceiver);
    }
}
